const db = require('../../config/db')
const jwt = require('jsonwebtoken')


const APPSECRET = '724a133cd300ceb5f4446584461d9bd3';
const ADMIN_APPSECRET = 'Ad' + APPSECRET + 'miN'
/**
 * 管理员登录
 * @param {*} req 
 * @param {*} res 
 */
exports.login = async (req, res) => {
  const { username, password } = req.body;

  console.log("username: ", username)
  console.log("password: ", password)

  // 这里验证管理员用户名密码，比如查数据库
  if (username === 'admin' && password === 'admin') {
    // 生成 token，有效载荷里放一些用户信息
    const payload = { username: 'admin', role: 'admin' };
    const token = jwt.sign(payload, ADMIN_APPSECRET, { expiresIn: '2h' }); // 2小时过期

    res.json({
      code: 0,
      message: '登录成功',
      token // 返回给前端
    });
  } else {
    res.status(401).json({
      code: 1,
      message: '用户名或密码错误'
    });
  }
};

/**
 * 管理员每次进入网站，判断token是否有效
 * @param {*} req 
 * @param {*} res 
 */
exports.checkToken =  async (req, res) => {
    res.json({ code: 0, message: 'token有效' })
}

/**
 * 管理员获取所有用户信息
 * 根据昵称，昵称没有就返回全部
 */
exports.getUserInfo = async(req, res) => {
  try {
    const {nickname} = req.body
    console.log("nickname: ", nickname)
    let sql
    let params = []
    if(nickname && nickname.trim() != "") {
      sql = `SELECT * FROM user where nickname LIKE ?`
      params.push(`%${nickname}%`)
    } else {
      sql = `SELECT * FROM user`
    }
    const [rows] = await db.query(sql, params)
    console.log("rows:", rows)
    res.status(200).json(
      rows.map(row => ({
        id: row.id,
        // avatarUrl: row.avatar_url,
        nickname: row.nickname,
        favoriteSports: row.favorite_sports,
        college: row.college,
        sport: row.sport,
        team: row.college + " - " + row.sport
      }))
    )
  } catch(err) {
    console.log("getUserInfo error: ", err)
    return res.status(500).json({"error": "服务器报错，请稍后重试!"})
  } 
}